import numpy as np
import pandas as pd
import yaml
from pandas import DataFrame
from yaml import SafeLoader

from datareport.api.DataSource import DataSource
from datareport.impl import StaticDF
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style



@style()
class ShiJi_KaiZhanChangCi_Zhibu_21(BaseParagraph):
    """
    支部来看
    """

    def __init__(self):
        super().__init__()
        self.text = '''(3)从支部来看:{}等{}个党支部年度开展组织生活场次最高，为{}次。\
'''
        self.sort = 12
        self.section=3

    def plot(self, df, plt):
        pass

    def getData(self,result):
        pass

    def start(self,conn,year,plt):
        df=StaticDF.getDF()
        count_df=df.groupby('partyBranchName')['num'].sum().reset_index(drop=False).sort_values('num',ascending=False).reset_index(drop=True)
        count_df['均值（/月）']=round(count_df['num']/12,1)

        self.tables.append(count_df.rename(columns={'partyBranchName':'党支部','num':'场次'}))
        ## 场次最高的党支部

        max_df=df[df['partyBranchName']==count_df['partyBranchName'].values[0]][['partyBranchName','month','num']]
        temp=max_df.groupby(['partyBranchName','month']).sum().reset_index(drop=False)

        self.tables.append(temp.rename(columns={'partyBranchName':'场次最大党支部','month':'月份','num':'场次'}))
        ## 场次最低的党支部
        min_df = df[df['partyBranchName'] == count_df['partyBranchName'].values[len(count_df)-1]][['partyBranchName','month','num']]
        temp = min_df.groupby(['partyBranchName', 'month']).sum().reset_index(drop=False)

        self.tables.append(temp.rename(columns={'partyBranchName': '场次最小党支部', 'month': '月份', 'num': '场次'}))
        ## 对这些党支部进行具体分析
        max_df['avg']=round(max_df['num']/12,1)
        self.text=self.text.format('、'.join(max_df['partyBranchName'].drop_duplicates().values),
                                   len(max_df['partyBranchName'].drop_duplicates()),
                                   count_df['num'].values[0],len(max_df)
                                   )

def maxmonth(x,df):
    temp=df[df['partyBranchName']==x]['month'].value_counts()
    return '、'.join(temp[temp==temp.max()].index.tolist())

def changci(x,df):
    temp=df[df['partyBranchName'] == x]['month'].value_counts()
    return temp.loc[temp.idxmax()]

def topic(x,df):
    temp=df[(df['partyBranchName']==x['partyBranchName']) & (df['month']==x['maxmonth'])]

    return temp['name'].value_counts().idxmax()

if __name__ == '__main__':
    with open('D:\work\sanhuiyike\datareport\config.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)
    con = DataSource(data['datasource']).conn
    ShiJi_KaiZhanChangCi_Zhibu_21().start(con, 2023, '')